package com.spit.hkpost

import android.bld.ScanManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import androidx.navigation.Navigation
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.spit.hkpost.base.BaseActivity
import com.spit.hkpost.bean.DataBean
import com.spit.hkpost.bean.RfidStateBean
import com.spit.hkpost.databinding.ActivityMainBinding
import com.spit.hkpost.mar.eventViewModel
import com.spit.hkpost.util.CacheUtil
import com.spit.hkpost.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Locale

class MainActivity : BaseActivity<RfidModel, ActivityMainBinding>() {

    val rfidModel: RfidModel by viewModels()

    var scanManager: ScanManager? = null

    override fun initView(savedInstanceState: Bundle?) {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, getColor(R.color.w_f4f9fd))

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                mViewModel.isOpen.value = false
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                if (!AppUtils.isAppForeground()) {
                    //app 进入后台
//                    mViewModel.isActive.set(false) //记录当前已经进入后台
                    mViewModel.isOpen.value = false
                }
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)

            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
            }

        })

        if (CacheUtil.isFirst()) {
            CacheUtil.setFirst(false)
            val displayName = LanguageUtils.getSystemLanguage().displayName
            if (displayName.contains("繁體")) {
                CacheUtil.setLanguage(1)
            } else if (displayName.contains("中文")) {
                CacheUtil.setLanguage(0)
            } else {
                CacheUtil.setLanguage(2)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        // rfid数据接收回调
        mViewModel.rfidData.observe(this, {
//            if (!mViewModel.isScan.get())return@observe
            var tagId = mViewModel.rfidData.value!!.TagId
            if (tagId.contains(" ")) {
                tagId = tagId.replace(" ", "")
            }
            LogUtils.e(tagId, it.Rssi)
            //搜索/识别回调
            if (mViewModel.tagFindParam == null) {
                rfidModel.epcData.value = RfidStateBean(
                    tagId = tagId,
                    rssi = it.Rssi
                )
            } else {
                rfidModel.epcSearchData.value = RfidStateBean(
                    tagId = tagId,
                    rssi = it.Rssi
                )
            }
        })

        //是否启动rdif
        mViewModel.isOpen.observe(this@MainActivity, { resultState ->
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                //啓動扫描才接串口
                /*if (resultState && mViewModel.initConn.get()) {
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                }else{
                    if (mViewModel.isScan.get()) {
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }*/
                //打開APP就接入串口, 当前已接入串口
                if (resultState) {
                    mViewModel.config()
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                } else {
                    if (mViewModel.isScan.get()) {
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }
            }
        })

        //指定搜索RFID
        mViewModel.isSearchOpen.observe(this, {
            if (com.blankj.utilcode.util.StringUtils.isEmpty(it)) {
                mViewModel.tagFindParam = null
                mViewModel.isOpen.value = false
            } else {
                mViewModel.tagFindParam = it
                mViewModel.isOpen.value = true
            }
        })

        mViewModel.language.observe(this, { languageSelected ->
            if (languageSelected < 0) return@observe
            when (languageSelected) {
                0 -> LanguageUtils.applyLanguage(Locale.SIMPLIFIED_CHINESE)
                1 -> LanguageUtils.applyLanguage(Locale.TRADITIONAL_CHINESE)
                2 -> LanguageUtils.applyLanguage(Locale.ENGLISH)
            }
            CacheUtil.setLanguage(languageSelected)
        })

    }
    var exitTime = 0L

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        LogUtils.e(keyCode, event)
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                if (event?.repeatCount == 0) {
                    mViewModel.longPressNext.set(false)
                    event.startTracking()
                    return true
                }
            }
            4 ->{
                val nav = Navigation.findNavController(this@MainActivity, R.id.nav_host_fragment)
                val currentDestinationId = nav.currentDestination?.id
                if (currentDestinationId != null && currentDestinationId != R.id.rfidParentFrg) {
                    nav.navigateUp()
                } else {
                    if (System.currentTimeMillis() - exitTime > 2000) {
                        ToastUtils.showShort("再按一次退出程序")
                        exitTime = System.currentTimeMillis()
                    } else {
                        finish()
                    }
                }
            }
        }
        return false
    }

    override fun onKeyLongPress(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                mViewModel.longPressNext.set(true)
                eventViewModel.longPressKeyCode.value = 1
                return true
            }
        }
        return super.onKeyLongPress(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            mViewModel.KEYCODE_MEDIA_NEXT.get() -> {
                if (!mViewModel.longPressNext.get()) {
                    eventViewModel.longPressKeyCode.value = 0
                } else {
                    eventViewModel.longPressKeyCode.value = 2
                    mViewModel.longPressNext.set(false)
                }
            }
        }
        return super.onKeyUp(keyCode, event)
    }

}